package com.example.freeengine.wallpaper.fragment;

import androidx.core.content.FileProvider;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.freeengine.R;
import com.example.freeengine.databinding.WallpaperFragmentBinding;
import com.example.freeengine.wallpaper.constants.WallPaperConstant;
import com.example.freeengine.wallpaper.constants.WallPaperUpdateStrategy;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * @author Terry Deng
 */
public class WallPaperFragment extends Fragment {

    private static final String TAG = WallPaperFragment.class.getSimpleName();
    private WallPaperViewModel mViewModel;
    private WallpaperFragmentBinding viewBiding;

    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int REQUEST_IMAGE_OPEN = 2;
    File imageFile;

    public static WallPaperFragment newInstance() {
        return new WallPaperFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        viewBiding = WallpaperFragmentBinding.inflate(inflater);
        return viewBiding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // fragment 中调用相机后 denial 错误解决
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
        mViewModel = new ViewModelProvider(requireActivity()).get(WallPaperViewModel.class);
        // 拍照
        viewBiding.tvWallpaperTakeAPicture.setOnClickListener(v -> {
            try {
                dispatchTakePictureIntent();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        // 查看拍照的照片
        viewBiding.ivWallpaperTakeAPicture.setOnClickListener(v -> {
            NavController navController = Navigation.findNavController(v);
            Bundle bundle = new Bundle();
            bundle.putString("path", requireContext().getExternalFilesDir("").getAbsolutePath() + WallPaperConstant.WALLPAPER_TAKE_A_PICTURE_FILE_PATH);
            navController.navigate(R.id.action_wallPaperFragment_to_pictureListFragment, bundle);
        });

        // 访问相册
        viewBiding.tvWallpaperPhotoalbum.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.setType("image/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            // Only the system receives the ACTION_OPEN_DOCUMENT, so no need to test.
            startActivityForResult(intent, REQUEST_IMAGE_OPEN);
        });
        // 查看相册添加的图片
        viewBiding.ivWallpaperPhotoalbum.setOnClickListener(v -> {
            NavController navController = Navigation.findNavController(v);
            Bundle bundle = new Bundle();
            bundle.putString("path", requireContext().getFilesDir() + WallPaperConstant.WALLPAPER_PHOTO_ALBUM_FILE_PATH);
            navController.navigate(R.id.action_wallPaperFragment_to_pictureListFragment, bundle);
        });

        // 循环一组照片
        viewBiding.tvWallpaperCyclerefresh.setOnClickListener(v -> {
            NavController navController = Navigation.findNavController(v);
            navController.navigate(R.id.action_wallPaperFragment_to_wallPaperCycleRefreshFragment);
        });

        // 每日更新
        viewBiding.tvWallpaperEverydayrefresh.setOnClickListener(v -> {
            NavController navController = Navigation.findNavController(v);
            navController.navigate(R.id.action_wallPaperFragment_to_wallPaperEveryDayRefreshFragment);
        });

    }

    private void dispatchTakePictureIntent() throws IOException {
        if(!requireActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)){
            Log.i(TAG, "PackageManager.FEATURE_CAMERA_ANY error");
        }
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(requireContext().getPackageManager()) != null ||
                requireActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
            Log.i(TAG, "dispatchTakePictureIntent: " + "start take picture");
            imageFile = mViewModel.createImageFile(new File(requireContext().getExternalFilesDir("").getAbsolutePath() +
                    WallPaperConstant.WALLPAPER_TAKE_A_PICTURE_FILE_PATH));
            Uri imageUri = FileProvider.getUriForFile(requireContext(), "com.example.freeengine.fileprovider", imageFile);
            // 获取完整照片
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }else {
            Log.i(TAG, "dispatchTakePictureIntent: " + "take picture error");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE) {
            // 未拍照直接返回，删除创建的文件
            if (resultCode == Activity.RESULT_CANCELED && imageFile != null){
                imageFile.delete();
            }
            return;
        }
        // 复制相册文件到本应用存储空间
        if (requestCode == REQUEST_IMAGE_OPEN && resultCode == Activity.RESULT_OK) {
            Uri fullPhotoUri = data.getData();
            File copyFile = null;
            try {
                copyFile = mViewModel.createImageFile(requireContext().getFilesDir() + WallPaperConstant.WALLPAPER_PHOTO_ALBUM_FILE_PATH);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try(FileOutputStream fos = new FileOutputStream(copyFile);
                InputStream fis = requireContext().getContentResolver().openInputStream(fullPhotoUri)){
                byte[] imageData = new byte[1024];
                int len;
                while ((len = fis.read(imageData)) > 0){
                    fos.write(imageData, 0, len);
                }
                Log.i(TAG, "onActivityResult: " + "photo file copy ok");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}